package su2010.puz.extractors;

import java.awt.image.BufferedImage;

import su2010.puz.Extractor;
import su2010.puz.Filter;
import su2010.puz.ImageHelper;
import su2010.puz.util.ImageCls;
import su2010.puz.util.PixelExtractor;

/**
 * Implementation of feature extractor which uses ratio of number of dark pixels
 * and number of all pixels in image, as a feature.
 *
 */
public class RatioExtractor implements Extractor {

	private BufferedImage image;
	private int interval_begin;
	private int interval_end;
	private int color_mode;
	private int numOutput = 1;
	private Filter[] filters1 = null;
	private Filter[] filters2 = null;
	private String name;
	
	public RatioExtractor() {
		this.interval_begin = 0;
		this.interval_end = 0;
		this.color_mode = ImageHelper.RED;
		this.name = "";
	}
	
	public RatioExtractor(String name) {
		this.interval_begin = 0;
		this.interval_end = 0;
		this.color_mode = ImageHelper.RED;
		this.name = name;
	}
	
	public void setInterval(int interval_begin, int interval_end) {
		this.interval_begin = interval_begin;
		this.interval_end = interval_end;
	}
	
	public void setColorMode(int mode) {
		this.color_mode = mode;
	}

	public void setFilters1(Filter ... filters){
		this.filters1 = filters;
	}
	
	public void setFilters2(Filter ... filters){
		this.filters2 = filters;
	}
	
	@Override
	public int getNumOutput() {
		return numOutput;
	}

	@Override
	public void setImage(ImageCls image) {
		this.image = image.getImage();	
	}

	public void setImage(BufferedImage image){
		this.image = image;
	}
	
	@Override
	public float[] extract() {
		BufferedImage image1;
		BufferedImage image2;
		image1 = ImageHelper.getBufferedImage(image);
		image2 = ImageHelper.getBufferedImage(image);
		if(filters1!=null)
			for(Filter filter : filters1)
				 image1 = filter.apply(image1);
		if(filters2!=null)
			for(Filter filter : filters2)
				 image2 = filter.apply(image2);
		//ImageHelper.showImage(image, "bla");
		int in_interval1 = 0;
		int in_interval2 = 0;
		int[][][] pixels1 = PixelExtractor.getRGBL(image1);
		int[][][] pixels2 = PixelExtractor.getRGBL(image2);
		int height = image1.getHeight();
		int width = image1.getWidth();
		int all = width*height;
		for(int i = 0; i< width;i++)
			for(int j = 0; j<height;j++)
				if(	pixels1[j][i][color_mode] >= interval_begin &&
					pixels1[j][i][color_mode] <= interval_end)
						in_interval1++;
		float r1 = (float)in_interval1/all;
		height = image2.getHeight();
		width = image2.getWidth();
		all = width*height;
		for(int i = 0; i< width;i++)
			for(int j = 0; j<height;j++)
				if(	pixels2[j][i][color_mode] >= interval_begin &&
					pixels2[j][i][color_mode] <= interval_end)
						in_interval2++;
		float r2 = (float)in_interval2/all;
		float[] ratio = new float[]{r1/r2};
		return ratio;
	}

	@Override
	public String getName() {
		return name;
	}

}
